package com.ta.util;

import com.ta.mapper.AddressMapper;
import com.ta.mapper.CartMapper;
import com.ta.mapper.UserMapper;
import com.ta.pojo.Address;
import com.ta.pojo.Cart;
import com.ta.pojo.User;
import com.ta.service.CartService;
import com.ta.service.ex.AddressException;
import com.ta.service.ex.CartException;
import com.ta.service.ex.UserNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.smartcardio.CardException;
import java.util.List;


public class ThrowServiceException {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private CartMapper cartMapper;
    /**
     * 抛出用户不存在异常
     * @param user
     * @return
     */
    public User findByUser(User user){
        User result = userMapper.findByUserName(user.getUsername());
        if (result == null || result.getIsDelete().equals(1)){
            throw new UserNotFoundException("用户名不存在");
        }
        return result;
    }

    /**
     * 抛出用户不存在异常
     * @param uid
     * @return
     */
    public User findByUser(Integer uid){
        User result = userMapper.findByUid(uid);
        if (result == null || result.getIsDelete().equals(1)){
            throw new UserNotFoundException("用户名不存在");
        }
        return result;
    }

    /**
     * 抛出地址不存在异常
     * @param aid
     */
    public void throwAddressNoFound(Integer aid){
        Address address = addressMapper.findByAid(aid);
        if (address == null){
            throw new AddressException("该地址已经不存在");
        }
    }

    /**
     * 抛出地址非法访问异常
     * @param aid
     * @param uid
     */
    public void throwAddressIllegalAccess(Integer aid, Integer uid){
        Address address = addressMapper.findByAidAndUid(aid, uid);
        if (address == null){
            throw new AddressException("非法访问");
        }
    }

    /**
     * 抛出购物车商品不存在异常
     * @param cid
     */
    public void throwCartNoFound(Integer cid){
        Cart cart = cartMapper.findByCid(cid);
        if (cart == null) {
            throw new CartException("当前商品已不存在！");
        }
    }

    /**
     * 抛出购物车商品非法操作
     * @param cid
     * @param uid
     */
    public void throwCartIllegalAccess(Integer cid, Integer uid){
        Cart cart = cartMapper.findByCid(cid);
        if (!cart.getUid().equals(uid)) {
            throw new CartException("该商品属于非法操作");
        }
    }
}
